package com.crawling.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;

public class ThreadPool {

    // 线程池维护线程的最少数量
    private static final int COREPOOLSIZE = 100;
    // 线程池维护线程的最大数量
    //private static final int MAXINUMPOOLSIZE = Integer.valueOf(Main.applicationContext.getBean(PropertieService.class).MAX_POOL_SIZE);
    private static final int MAXINUMPOOLSIZE = 1800;
    // 线程池维护线程所允许的空闲时间
    private static final long KEEPALIVETIME = 4;
    // 线程池维护线程所允许的空闲时间的单位
    private static final TimeUnit UNIT = TimeUnit.SECONDS;
    // 线程池所使用的缓冲队列,这里队列大小为3
    private static final BlockingQueue<Runnable> WORKQUEUE = new ArrayBlockingQueue<Runnable>(1000000);
    // 线程池对拒绝任务的处理策略：AbortPolicy为抛出异常；CallerRunsPolicy为重试添加当前的任务，他会自动重复调用execute()方法；DiscardOldestPolicy为抛弃旧的任务，DiscardPolicy为抛弃当前的任务
    //private static final AbortPolicy HANDLER = new ThreadPoolExecutor.AbortPolicy();
    private static final ThreadPoolExecutor.CallerRunsPolicy HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

    private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(COREPOOLSIZE, MAXINUMPOOLSIZE, KEEPALIVETIME, UNIT, WORKQUEUE, HANDLER);

    /**
     * 加入到线程池中执行
     *
     * @param runnable
     */
    public static void runInThread(Runnable runnable) {
        threadPool.execute(runnable);
    }

    public static boolean isTerminated() {
        return threadPool.isTerminated();
    }

    public static int getActiveCount() {
        return threadPool.getActiveCount();
    }

    public static long getCompletedTaskCount() {
        return threadPool.getCompletedTaskCount();
    }

    public static int getCorePoolSize() {
        return threadPool.getCorePoolSize();
    }

    public static int getLargestPoolSize() {
        return threadPool.getLargestPoolSize();
    }

    public static long getTaskCount() {
        return threadPool.getTaskCount();
    }

    public static int getQueueSize() {
        return threadPool.getQueue().size();
    }

    public static int getPoolSize() {
        return threadPool.getPoolSize();
    }

    public static int getMaximumPoolSize() {
        return threadPool.getMaximumPoolSize();
    }


    static ExecutorService executor = Executors.newFixedThreadPool(50);

    public static void main(String[] args) {
        for (int i = 0; i < 3000; i++) {
            System.out.println("time:"+new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date()));
            receiverAuditUser();
        }
    }
    static  int count=0;
    private static void receiverAuditUser() {
        executor.execute(() -> {
            System.out.println(count++);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程" + Thread.currentThread().getName());
        });
    }

}
